import jwt
import time
from django.contrib.auth.hashers import make_password, check_password
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from user.serializer import UserSerializer, AddrSerializer
from take_out_food import settings
from user.models import User, Address


# 注册
class Register(APIView):
    def post(self,request):
        # 前端获取信息
        name = request.data.get('username')
        mobile = request.data.get('mobile')
        password = request.data.get('password')

        if not all([name,mobile,password]):
            return Response({'code':400,'msg':'请补全信息'})

        # 密码加密
        pwd = make_password(password)
        user = User.objects.create(username=name,password=pwd,mobile=mobile)
        user.save()

        return Response({
            'code':200,'msg':'注册成功'
        })


# 用户登录
class Login(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not all([username,password]):
            return Response({"code":200,'msg':'请补全登录信息'})

        user = User.objects.get(username=username)
        if not user:
            return Response({'code': 400, 'msg': '没有此用户 请先注册'})

        if not check_password(password,user.password):
            return Response({'code':400,'msg':'密码错误'})

        payload = {'id': user.id, 'name': user.username, 'time': int(time.time()) + 6480000}
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        return Response({
            'code':200,'msg':'登陆成功',
            'token':token
        })


# 退出登录
class Logout(APIView):
    def post(self, request):
        # 删除cookie
        token = request.COOKIES.get('token')
        if token:
            del token
        return Response({'msg': '退出成功', 'code': 200})


# 检测用户登录的装饰器
def check_user(func):
    def check(cls,request):
        token = request.META.get('HTTP_TOKEN')
        try:
            payload = jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
            if payload['time'] < int(time.time()):
                return Response({'code':400,'msg':'token失败'})
        except Exception as e:
            return Response({'code':400,'msg':'验证失败'})
        return func(cls,request,payload)
    return check


# 用户
class UserInfo(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'


    # 重写create方法
    def create(self,request,*args,**kwargs):
        username = request.data.get('username')
        sex = request.data.get('sex')
        info = request.data.get('info')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        id_number = request.data.get('id_number')
        user = User.objects.filter(id_number=id_number).first()
        if user:
            return Response({'code':400,'msg':'用户已经存在'})
        ser = User.objects.create(username=username,sex=sex,info=info,mobile=mobile,password=password,id_number=id_number)
        ser.save()
        return Response({'code':200,'msg':'添加成功'})

    # 重写update方法
    # def update(self, request, *args, **kwargs):
    #     if not request.data.get('name'):
    #         name = User.objects.get(id=request.data['id']).username
    #         request.data['username']=name
    #         return super().update(request,*args,**kwargs)
    #     return super().update(request,*args,**kwargs)



# 展示用户/商家详情
class UserView(APIView):
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        user_info = User.objects.all()  # 获取用户
        if not user_info:
            return Response({'code': 400, 'msg': '用户不存在'})
        ser = UserSerializer(user_info,many=True)
        # todo  前端写一个判断开关展示具体内容
        # user_list = []
        # for user in user_info:
        #     a = {
        #         'name':user.username,
        #         'mobile':user.mobile,
        #         'pwd':user.password,
        #         'sex':user.sex,
        #         'id_number':user.id_number,
        #         'time':user.create_time,
        #         'info':user.info
        #     }
        #     user_list.append(a)
        return Response({
            'code':200,'msg':ser.data
        })

    @check_user
    def put(self,request,payload):
        user_id = payload['id']
        user_info = User.objects.filter(id=user_id).first()

        if not user_info:
            return Response({
                'code':400,'msg':'用户不存在'
            })

        ser = UserSerializer(instance=user_info, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()

        return Response({
            'code':200,'msg':'更新成功'
        })



    @check_user
    def delete(self,request,payload):
        user_id = payload['id']
        User.objects.filter(id=user_id).delete()
        return Response({'code':200,'msg':'删除成功'})


# 地址
class UserAdder(APIView):
    @check_user
    def get(self,request,paLoad):
        # user_id = request.data.get('id')
        # print(user_id)
        user_id = paLoad['id']
        user_info = User.objects.filter(id=user_id).first() # 获取用户
        if not user_info:
            return Response({'code':400,'msg':'用户不存在'})

        address_all = Address.objects.filter(user_id=user_info.id).all()
        ser = AddrSerializer(address_all,many=True)
        # address_list = []
        #
        # for addr in address_all:
        #     address = {
        #         'id':addr.id,
        #         'address':addr.address,
        #         'address_detailed':addr.address_detailed,
        #         'longitude':addr.longitude,
        #         'latitude':addr.latitude,
        #     }
        #     address_list.append(address)
        # print(address_list)
        return Response({
            'code':200,'msg':'地址获取成功',
            # 'data':address_list
            'data':ser.data
        })

    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        address = request.data.get('address')
        longitude = request.data.get('longitude')
        address_detailed = request.data.get('address_detailed')
        latitude = request.data.get('latitude')
        is_atter = request.data.get('is_atter')
        user = request.data.get('user_id')
        address_info = Address.objects.create(
            address=address,
            user_id_id=user,
            longitude=longitude,
            address_detailed=address_detailed,
            latitude=latitude,
            is_atter=is_atter,
        )

        return Response({
            'code':200,'msg':'新增地址成功',
            'addr':address_info.address
        })


    @check_user
    def put(self,request,payload):
        user_id = payload['id'] # 获取用户id
        addr = Address.objects.filter(id=user_id).first()
        ser = AddrSerializer(instance=addr,data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code':200,'msg':'更新成功'})


    # @check_user
    # def delete(self,request, payload):
    #     user_id = payload['id']
    #     Address.objects.filter(id=user_id).delete()
    #     return Response({'code':200,'msg':'删除成功'})

    @check_user
    def delete(self, request, payload):
        user_id = payload['id']
        addr_id = request.data.get('id')
        # print(user_id, addr_id)
        addr_info = Address.objects.filter(id=addr_id, user_id=user_id).first()
        # print('11111', addr_info)
        addr_info.delete()
        return Response({'code': 200, 'msg': '地址删除成功'})

# 用户修改密码
class Password(APIView):
    def put(self,request,payload):
        user_id = payload['id']
        old_password = request.data.get('old_pwd')
        new_pwd = request.data.get('pwd')
        two_pwd = request.data.get('password')
        user = User.objects.filter(id=user_id).first()
        if not user:
            return Response({
                'code':400,'msg':'用户不存在'
            })
        check = check_password(old_password,user.password)
        if not check:
            return Response({
                'code':400,'msg':'原始密码输入错误'
            })
        if new_pwd != two_pwd:
            return Response({
                'code':400,'msg':'请重新输入密码'
            })
        user.set_password(new_pwd)
        user.save()
        return Response({
            'code':200,'msg':'密码修改成功'
        })